import time
from src.LossCalculator import LossCalculator
from src.exts import delayfunc
from src.spider import Spider
from src.mxtf_api import MxtfApi

import socket

def get_local_ip():
    try:
        # 创建一个UDP套接字
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # 连接到一个公共的IP地址和端口（这里使用Google的公共DNS服务器）
        sock.connect(("8.8.8.8", 80))
        # 获取本地IP地址
        local_ip = sock.getsockname()[0]
    finally:
        # 关闭套接字
        sock.close()
    return local_ip

@delayfunc()
def fetch_sw_index_daily(logger):
    try:
        s = Spider()
        s.fetch_sw_index_daily()
        logger.info(f"爬取申万行业指数历史行情全部完成")
    except Exception as e:
        logger.info(f"call fetch_sw_index_daily error:{str(e)}")
@delayfunc()
def fetch_hist_sw_ind_comp(logger):
    try:
        s = Spider()
        s.fetch_hist_sw_ind_comp()
    except Exception as e:
        logger.info(f"call fetch_hist_sw_ind_comp error:{str(e)}")
    
@delayfunc()
def fetch_sw_ind(logger):
    try:
        s = Spider()
        s.fetch_sw_ind()
        logger.info(f"爬取shenwan_history全部完成")
    except Exception as e:
        logger.info(f"call fetch_sw_ind error:{str(e)}")
    
@delayfunc()
def fetch_stock_daily(start_date,stock=None,logger=None):
    try:
        s = Spider(logger)
        stocks = []
        if stock:
            stocks.append(stock)
        s.fetch_stock_daily_all(start_date,stocks)
        logger.info(f"爬取股票开盘数据全部完成")
    except Exception as e:
        logger.info(f"call fetch_stock_daily error:{str(e)}")

@delayfunc()
def fetch_fuquan_all(stock=None,logger=None):
    try:
        s = Spider(logger)
        stocks = []
        if stock:
            stocks.append(stock)
        s.fetch_fuquan_all(stocks)
        logger.info(f"爬取复权因子全部完成")
    except Exception as e:
        logger.info(f"call fetch_stock_daily error:{str(e)}")
        
@delayfunc()
def fetch_fuquan_daliy(logger=None):
    try:
        s = Spider(logger)
        s.fetch_fuquan_daliy()
        logger.info(f"每日爬取复权因子全部完成")
    except Exception as e:
        logger.info(f"call fetch_stock_daily error:{str(e)}")
   
@delayfunc()
def fetch_stocks(logger=None):
    try:
        s = Spider(logger)
        s.fetch_stocks()
        logger.info(f"爬取股票信息全部完成")
    except Exception as e:
        logger.info(f"call fetch_stock_daily error:{str(e)}") 

@delayfunc()
def pre_caculator(cl_trd_hist_json,callback=True,logger=None):
    logger.debug("begin pre_caculator")
    try:
        loss_calculator = LossCalculator(cl_trd_hist_json,False,logger=logger)
        loss_calculator.Caculate(callback)
        logger.info(f"预测计算完成")
    except Exception as e:
        logger.error(f"call pre_caculator error:{str(e)}")
    
@delayfunc()
def fetch_all_measure_history(logger):
    try:
        logger.info(f"开始爬监管数据")
        s = Spider()
        s.fetch_all_measure_history()
        logger.info(f"爬监管数据全部完成")
    except Exception as e:
        logger.error(f"爬监管数据报错 error:{str(e)}")
        
@delayfunc()
def fetch_overall_market_trend(logger):
    try:
        s = Spider()
        s.fetch_overall_market_trend()
        logger.info(f"爬取大盘数据全部完成")
    except Exception as e:
        logger.error(f"爬监大盘据报错 error:{str(e)}")

def calculate_hanlder(logger,taskId):
    try:
        local_ip = get_local_ip()
        api = MxtfApi()
        result = api.get_task(local_ip,taskId)
        data = result.get("data")
        if not data:
            return
        loss_calculator = LossCalculator(data,False,logger=logger)
        loss_calculator.Caculate(True)
    except Exception as e:
        logger.error(f"测算失败 error:{str(e)}")
        time.sleep(1)
@delayfunc()
def task_worker(logger):
    try:
        # 示例调用
        local_ip = get_local_ip()

        logger.info(f"{local_ip}开始执行测算任务")
        api = MxtfApi()
        while True:
            try:
                result = api.get_task(local_ip)
                data = result.get("data")
                if not data:
                    time.sleep(5)
                    continue   
                loss_calculator = LossCalculator(data,False,logger=logger)
                loss_calculator.Caculate(True)
            except Exception as e:
                logger.error(f"测算失败 error:{str(e)}")
                time.sleep(1)

    except Exception as e:
        logger.error(f"测算失败 error:{str(e)}")